﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
//using System.Management;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
using SysLog;

namespace Infrastructure.Common
{
    public class ComputerInfo
    {
        //public static List<string> GetMacByWMI()
        //{
        //    List<string> macs = new List<string>();
        //    string mac = "";
        //    using (ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"))
        //    using (ManagementObjectCollection moc = mc.GetInstances())
        //    {
        //        foreach (ManagementObject mo in moc)
        //        {
        //            if ((bool)mo["IPEnabled"])
        //            {
        //                mac = mo["MacAddress"].ToString();
        //                macs.Add(mac);
        //            }
        //        }
        //    }

        //    return macs;
        //}

        public static bool IsVerifyCodeAuthed()
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + "\\VerifyCode.txt";
            string sign, md5Str;
            if (File.Exists(path))
            {
                sign = File.ReadAllText(path);
                md5Str = mac();
                if (sign.ToUpper() == md5Str.ToUpper())//sign值是自己加密过的
                {
                    LogHelper.Info("授权成功.");
                    return true;
                }
                LogHelper.Fatal("授权文件VerifyCode.txt授权失败 !");
            }
            else
            {
                LogHelper.Fatal("缺少授权文件 VerifyCode.txt !");
            }
            return false;
        }

        public static string mac()
        {
            List<string> mac = GetActiveMacAddress(":");
            string Macs = mac[0];//物理地址. . . . . . . . . . . . . : 54-04-A6-97-15-13
            Macs = Macs.Substring(Macs.Length - 17);
            string macencrypt = Md5Hash(Macs).ToString();
            string Qmac = macencrypt + "StrongSoftGPRSAcqService";
            string Qencrypt = Md5Hash(Qmac).ToString();
            return Qencrypt;
        }

        private static string Md5Hash(string input)
        {
            MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
            byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));
            StringBuilder sBuilder = new StringBuilder();
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }
            return sBuilder.ToString();
        }

        public static List<string> GetActiveMacAddress(string separator = "-")
        {
            NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();

            //Debug.WriteLine("Interface information for {0}.{1}  ",
            // computerProperties.HostName, computerProperties.DomainName);
            if (nics == null || nics.Length < 1)
            {
                Debug.WriteLine(" No network interfaces found.");
                return null;
            }

            var macAddress = new List<string>();

            //Debug.WriteLine(" Number of interfaces .................... : {0}", nics.Length);
            foreach (NetworkInterface adapter in nics.Where(c =>
             c.NetworkInterfaceType != NetworkInterfaceType.Loopback && c.OperationalStatus == OperationalStatus.Up))
            {
                //Debug.WriteLine("");
                //Debug.WriteLine(adapter.Name + "," + adapter.Description);
                //Debug.WriteLine(string.Empty.PadLeft(adapter.Description.Length, '='));
                //Debug.WriteLine(" Interface type .......................... : {0}", adapter.NetworkInterfaceType);
                //Debug.Write(" Physical address ........................ : ");
                //PhysicalAddress address = adapter.GetPhysicalAddress();
                //byte[] bytes = address.GetAddressBytes();
                //for (int i = 0; i < bytes.Length; i++)
                //{
                // // Display the physical address in hexadecimal.
                // Debug.Write($"{bytes[i]:X2}");
                // // Insert a hyphen after each byte, unless we are at the end of the 
                // // address.
                // if (i != bytes.Length - 1)
                // {
                //  Debug.Write("-");
                // }
                //}

                //Debug.WriteLine("");

                //Debug.WriteLine(address.ToString());

                IPInterfaceProperties properties = adapter.GetIPProperties();

                var unicastAddresses = properties.UnicastAddresses;
                if (unicastAddresses.Any(temp => temp.Address.AddressFamily == AddressFamily.InterNetwork))
                {
                    var address = adapter.GetPhysicalAddress();
                    if (string.IsNullOrEmpty(separator))
                    {
                        macAddress.Add(address.ToString());
                    }
                    else
                    {
                        macAddress.Add(string.Join(separator, address.GetAddressBytes().Select(b => Convert.ToString(b, 16).PadLeft(2, '0').ToUpper())));
                    }
                }
            }

            return macAddress;
        }
    }
}
